﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using Relocation.Data;
using Relocation.Com;

using Relocation.Com.Tools;
using Relocation.UI.Interface;
using Relocation.Base;

namespace Relocation.UI
{

	public partial class HousesList : HouseListHelp, IPrintForm
	{

		#region 构造函数
		public HousesList()
			: base()
		{
			InitializeComponent();
			Initialize();			
		}

		public HousesList(Session session)
			: base(session)
		{
			InitializeComponent();
			Initialize();			
		}

		#endregion

		#region 初始化、加载

		private void Initialize()
		{
			this.BindingSource.DataSourceChanged += new System.EventHandler(this.housesBindingSource_DataSourceChanged);
			this.S_text_houses_code.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t=>t.house_code)));
			this.S_text_storeroom.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.storeroom)));
			this.S_comboBoxDistrict.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.district)));
			this.S_comboBoxState.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.isUsed), SearchInfo.SearchFieldTypes.Number, new SearchInfo.RanderHandler(delegate(Control control)
			{
				if (string.IsNullOrEmpty(control.Text.Trim()))
					return "";
				return control.Text.Equals("未分配") ? "false" : control.Text.Equals("已分配") ? "true" : "";
			}), new SearchInfo.ReseterHandler(delegate(Control control)
			{
				if (control == null)
					return;
				control.Text = "全部";
			})));
			this.SortField = House.GetPropName(t => t.updated);
			this.SortDirection = ListSortDirection.Descending;
			this.ObjectQuery = this.Session.DataModel.Houses.Where("it."+House.GetPropName(t=>t.project_id)+"="+this.Session.Project.project_id.ToString());
			this.ObjectQuerySearch = this.ObjectQuery.Where("it." + House.GetPropName(t => t.isUsed) + "=false");			
			ControlTag roleTag=new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN,Session.KEY_ROLE_OPERATOR));
			this.ButtonAdd.Tag = roleTag;
			this.ButtonEdit.Tag = roleTag;
			this.ButtonDel.Tag = roleTag;
		}

		/// 初始化地区下拉框
		/// </summary>
		public void InitComboBox()
		{
			try
			{				
				List<string> districts =  this.ObjectQuery.Where(it=>it.district!=null&&it.district!="").OrderBy(t => t.updated).Select(t => t.district).Distinct().ToList();	
				districts.Insert(0,"");
				this.S_comboBoxDistrict.DataSource =districts;
				this.S_comboBoxState.SelectedIndex = 0;
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
			}
		}


		/// <summary>
		/// 窗体加载
		/// </summary>
		private void HousesList_Load(object sender, EventArgs e)
		{
			try
			{
				InitComboBox();				
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
			}
		}

		/// <summary>
		/// 刷新数据
		/// </summary>
		public override void Refresh()
		{
			try
			{
				this.Reload();
				InitComboBox();
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
			}
		}

		#endregion



		#region 增、删、改
		/// <summary>
		/// 添加按钮
		/// </summary>        
		private void ButtonAdd_Click_1(object sender, EventArgs e)
		{
			try
			{
				using (HousesWindow window = new HousesWindow(this.Session))
				{
					if (DialogResult.OK.Equals(window.ShowDialog(this)))
						this.Reload();
				}				
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error("操作失败！");
			}
		}

		/// <summary>
		/// 修改按钮
		/// </summary>        
		private void ButtonEdit_Click(object sender, EventArgs e)
		{
			try
			{
				House houses = this.GetSelectEntity();
				if (houses != null)
				{
					HousesWindow window = new HousesWindow(Session, houses);
					if (window.ShowDialog(this).IsOK())
					{
						this.Reload();
					}
				}
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error(ex);
			}
		}

		/// <summary>
		/// 删除按钮
		/// </summary>		
		private void ButtonDel_Click(object sender, EventArgs e)
		{
			try
			{
				House houses = this.GetSelectEntity();
				if (houses == null)
					return;
				if (MyMessagebox.Confirm("您确定要删除吗？").IsYes())
				{		
					if (houses.IsUsed())
					{
						MyMessagebox.Show("安置房已被使用，无法删除！");
						return;
					}
					this.Session.DataModel.Delete(houses);
				}
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error("删除失败！");
			}
			this.Reload();
		}

		#endregion


		#region DataGridView事件

		/// <summary>
		/// 数据绑定改变（刷新序号）
		/// </summary>		
		private void housesBindingSource_DataSourceChanged(object sender, EventArgs e)
		{
			try
			{
				House house = new House();
				house.area1 = this.ObjectQuerySearch.Sum(t => t.area1);
				house.area2 = this.ObjectQuerySearch.Sum(t => t.area2);
				house.streetArea = this.ObjectQuerySearch.Sum(t => t.streetArea);
				house.carbarnArea = this.ObjectQuerySearch.Sum(t=>t.carbarnArea);
				this.BindingSource.Add(house);
				this.DataGridView.Rows[this.DataGridView.Rows.Count - 1].Cells[this.Column_Index.Name].Value = "总计：";
			}
			catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
			}
		}
		protected override string Entity2ToolTipText(House entity, string remarkName = "remark")
		{
			return base.Entity2ToolTipText(entity, remarkName);
		}

		/// <summary>
		/// 弹出对应拆迁户
		/// </summary>		
		private void housesDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			try
			{
				if (e.RowIndex < 0)
					return;
				string dataPropertyName = DataGridView.Columns[e.ColumnIndex].DataPropertyName;
				if (string.IsNullOrEmpty(dataPropertyName) || !dataPropertyName.Equals(House.GetPropName(t=>t.isUsed)))
					return;
				House house = this.GetSelectEntity();				
				Relocatees_House relocatees_House = house.GetRelocateHouse().FirstOrDefault();
				if (relocatees_House == null)
					return;				
				RelocateesWindow rWindow = new RelocateesWindow(this.Session, relocatees_House.GetRelocate());				
				rWindow.Text = "安置情况";
				rWindow.MinimumSize = new System.Drawing.Size(800, 600);
				rWindow.LoadEntity(relocatees_House);
				rWindow.ShowDialog(this);
			}
			catch (Exception ex)
			{
				Log.Error(ex);
				MyMessagebox.Error(ex.Message);
			}
		}

		/// <summary>
		/// 格式化内容
		/// </summary>		
		private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			string _name = this.DataGridView.Columns[e.ColumnIndex].Name;			
			if (_name.Equals(this.Column_Index.Name))
			{				
				if (e.Value == null)
				{
					e.Value = (e.RowIndex + 1).ToString();
					e.FormattingApplied = true;
				}
			}			
			else if (_name.Equals(this.relocateesHouseDataGridViewTextBoxColumn.Name))
			{				
				House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House;
				if (house == null||house.isUsed == false)
					return;

				//house.Relocatees_House.Load();
				Relocatees_House relocate_House = house.Relocatees_House.FirstOrDefault();
				if (relocate_House == null)
					return;
                relocate_House.LoadRelocate();			
				if (relocate_House.Relocatee == null)
					return;
				e.Value = relocate_House.Relocatee.head;
				e.FormattingApplied = true;
				
			}
			else if (_name.Equals(this.isUsedDataGridViewCheckBoxColumn.Name))
			{
				House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House;
				e.Value = house == null ? string.Empty : house.isUsed ? "已分配" : string.Empty;									
			}
            else if (_name.Equals(this.organizationDataGridViewTextBoxColumn.Name))
            {
                House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House;
                if (house == null || house.isUsed == false)
                    return;

                Relocatees_House relocate_House = house.Relocatees_House.FirstOrDefault();
                if (relocate_House == null)
                    return;
                relocate_House.LoadRelocate();
                if (relocate_House.Relocatee == null)
                    return;
                e.Value = relocate_House.Relocatee.organization;
                e.FormattingApplied = true;
            }

		}

		#endregion
	
	
		#region IPrintForm 成员

		public void Print()
		{
			ExcelHelp.DataGridToExcel(this.DataGridView);
		}

		#endregion		
				
	}
}
